package lottery

import (
	"fmt"
	"math/rand"

	"github.com/molio/practice/ds/link"
)

// 奖池初始化仅有10人，仅有一人能得到一张马尔代夫旅行券,随机报数，报到谁谁被淘汰直到只剩下一人,模拟上述过程

type Lottery struct {
	Num              int                            // 参与抽奖的人数
	CircularSequence *link.CircularSingleLinkedList // 排队循环队列
}

func NewLottery(nlen int) *Lottery {
	csll := link.NewCircularSingleLinkedList()
	csll.CreateCircularSingleLinkedList(true, nlen)
	return &Lottery{Num: nlen, CircularSequence: csll}
}

func (l *Lottery) getTransNum() int {
	num := (rand.Intn(100) + 1) % l.Num
	if num == 0 {
		return l.Num
	}
	return num
}

func (l *Lottery) LotteryBegin() {
	fmt.Println("开始抽奖...")
	for l.CircularSequence.GetLength() > 1 {
		fmt.Println("============================")
		fmt.Printf("奖池中还有%d人参与抽奖\n", l.Num)
		l.CircularSequence.TravelCircularSingleLinkedList()
		transNum := l.getTransNum()
		fmt.Printf("本轮淘汰 %d 位置上的人\n", transNum)
		node := l.CircularSequence.FindElemnentByPos(transNum)
		l.CircularSequence.DeleteElement(node.Data)
		l.Num -= 1
		fmt.Println("============================")
	}
}

func LotteryRun() {
	l := NewLottery(10)
	fmt.Println("参与抽奖的有以下：")
	l.CircularSequence.TravelCircularSingleLinkedList()
	l.LotteryBegin()
	fmt.Printf("最终由%d获得马尔地夫旅行券\n", l.CircularSequence.Head.Next.Data)
}
